package com.butterfly.hotkey.client.core.netty;

import com.butterfly.hotkey.core.constant.Constants;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.butterfly.hotkey.core.constant.Constants.DELIMITER;
import static com.butterfly.hotkey.core.constant.Constants.MAX_LENGTH;

/**
 * Client客户端，需保持单例
 *
 * @author butterfly
 * @version 1.0
 */
public class AppNettyClient {

    private static final Logger log = LoggerFactory.getLogger(Constants.CLIENT);

    private final Bootstrap bootstrap;
    private final AppNettyClientHandler nettyClientHandler;

    public AppNettyClient(AppNettyClientHandler nettyClientHandler) {
        this.nettyClientHandler = nettyClientHandler;
        this.bootstrap = initBootstrap();
    }

    private Bootstrap initBootstrap() {
        EventLoopGroup group = new NioEventLoopGroup(2);

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER.getBytes());
                        ch.pipeline()
                                .addLast(new DelimiterBasedFrameDecoder(MAX_LENGTH, delimiter))
                                // 可更换编码方式
                                .addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new IdleStateHandler(0, 0, 30))
                                .addLast(nettyClientHandler);
                    }
                });
        return bootstrap;
    }

    /**
     * 连接制定的worker地址
     *
     * @param ip   ip
     * @param port port
     * @return Channel
     */
    public Channel connect(String ip, int port) {
        try {
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
            return channelFuture.channel();
        } catch (Exception e) {
            log.error("worker {}:{} can not connect", ip, port, e);
        }

        return null;
    }

}
